package com.knowledge.review.jucReview;

import sun.misc.Unsafe;
import java.lang.reflect.Field;

/**
 * @author XFW
 * @date 2024/6/21 14:30
 * @Description UnsafeMemoryExample及逆行内存分配示例
 **/
public class UnsafeMemoryExample {
    private static final Unsafe UNSAFE;
    private static final long SIZE = 4;

    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNSAFE = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        long memoryAddress = UNSAFE.allocateMemory(SIZE);
        UNSAFE.putInt(memoryAddress, 42);

        int value = UNSAFE.getInt(memoryAddress);
        System.out.println("Value: " + value);

        UNSAFE.freeMemory(memoryAddress);
    }
}
